package com.wjw.java.thread;

/**
 * 线程常用方法2：
 * --------------------------------------------------------------------------------------
 * 1.yield();
 *   线程的礼让,让出CPU,让其他线程先执行,但礼让时间不确定,所有也不一定礼让成功
 * 2.join();
 *   线程插队,插队的线程一旦插队成功,则先执行插队线程中的所有代码
 *
 * --------------------------------------------------------------------------------------
 */
public class ThreadMethod2 {
    public static void main(String[] args) {
        useYield();
        //useJoin();
    }

    //1.线程礼让,礼让不一定成功
    public static void useYield(){
        //子线程
        T3 t3 = new T3();
        Thread thread1 = new Thread(t3,"子线程");
        thread1.start();

        //main线程,每秒输出一次,当i==5的时候,线程礼让,礼让不一定成功
        String name = Thread.currentThread().getName();
        for (int i = 0; i < 10; i++) {
            if(i == 5){
               Thread.yield();
            }
            System.out.println(name+"：正在运行..."+(i+1));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //2.线程插队,直接插队
    public static void useJoin(){
        //子线程
        T3 t3 = new T3();
        Thread thread1 = new Thread(t3,"子线程");
        thread1.start();

        //main线程,每秒输出一次,当i==5的时候,让子线程插队,子线程先执行完
        String name = Thread.currentThread().getName();
        for (int i = 0; i < 10; i++) {
            if(i == 5){
                try {
                    thread1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(name+"：正在运行..."+(i+1));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class T3 implements Runnable{
    int num = 0;

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        while (true){
            if(num == 15){
                break;
            }
            try {
                System.out.println(name+"正在运行..."+(++ num));
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}